import * as api from '../../api/api.js';
import db from '../../utils/db.js';
import { ASSETS } from '../../config.js';
import { getTsTimestamp, getYsTimestamp } from '../../utils/util.js';
const app = getApp();
const os = app.os;

Page({
  data: {
    assets: ASSETS,
    appType: app.globalData.appType,
    imId: app.globalData.imId, // 客服抖音号
    showAdddeskBtn: app.globalData.showAdddeskBtn,
    topHeight: 0,
    isFixedNav: false,
    platformImType: 'group_buy',
    showEdit: false,
    checkedIds: [],
    checkedAll: false,
    currentPage: 1,
    pageTotal: 1,
    limit: 12,
    dataType: 1,
    isEnd: false,
    isEmpty: false,
    isLoading: true,
    timeData: [],
    dataList:[],
    seenList:[],
    collectList:[]
  },

  onLoad: function (options) {
    os.setNavigationBarTitle({
      title: app.globalData.appName
    });
    os.hideShareMenu();
  },

  onReady: function () {
    let res = os.getMenuButtonBoundingClientRect();
    this.setData({
      topHeight: (res.bottom || 90) + 10
    });

    app.sendAppLogs('app', 3); // 日志
  },

  onShow: function () {
    this.setData({
      imId: app.globalData.imId,
      showAdddeskBtn: app.globalData.showAdddeskBtn,
      appType: app.globalData.appType,
      currentPage: 1
    });
    this.getDataList();
    app.delayAdDialog();
  },

  /**
   * 页面隐藏
   */
  onHide() {
    app.delayAdDialog(false);
  },

  /**
   * 获取数据
   */
  getDataList: function () {
    const that = this;

    if (this.data.dataType == 2) {
      this.getSeenData();
      return;
    }

    // os.showNavigationBarLoading({});
    api.getCollectList({
      page: that.data.currentPage,
      limit: that.data.limit,
      type: that.data.dataType
    }).then(res => {
      // os.hideNavigationBarLoading({});
      let dataList = that.data.dataList;
      let timeData = [];
      let isEnd = false;
      let isEmpty = false;
      let isLoading = false;
      if (res.code == 200) {
        if(res.data.current_page == 1){
          dataList = [];
          if(that.data.dataType == 1){
            that.setData({collectList: res.data.list});
          }else{
            that.setData({seenList: res.data.list});
          }
        }
        if(res.data.list.length > 0){
          dataList = dataList.concat(res.data.list);
        }
        if(res.data.current_page >= res.data.total_page && res.data.count > 0){
          isEnd = true;
        }
        if(res.data.current_page < res.data.total_page && res.data.count > 0){
          isLoading = true;
        }
        if(dataList.length == 0){
          isEmpty = true;
        }
        if(that.data.dataType == 2 && dataList.length > 0){
          const tstime = getTsTimestamp();
          const ystime = getYsTimestamp();
          let today = {title: '今天', start_id: 0};
          let ytoday = {title: '昨天', start_id: 0};
          let gtoday = {title: '更早', start_id: 0};
          dataList.forEach(item => {
            if(item.update_time >= tstime){
              if(today.start_id == 0){
                today.start_id = item.id;
                timeData.push(today);
              }
            }
            if(item.update_time < tstime && item.update_time >= ystime){
              if(ytoday.start_id == 0){
                ytoday.start_id = item.id;
                timeData.push(ytoday);
              }
            }
            if(item.update_time < ystime){
              if(gtoday.start_id == 0){
                gtoday.start_id = item.id;
                timeData.push(gtoday);
              }
            }
          });
        } else {
          dataList.forEach(item => {
            item.last_num = db.getSeenLastNum(item.playlet_id, item.last_num);
          });
        }
        
        that.setData({
          dataList: dataList, 
          currentPage: parseInt(res.data.current_page), 
          pageTotal: res.data.total_page,
          timeData: timeData,
          isEnd: isEnd,
          isEmpty: isEmpty,
          isLoading: isLoading
        });
      }else{
        that.setData({
          isEmpty: true,
          isLoading: isLoading
        });
        return app.Tips({title: res.msg});
      }
    }).catch(err => {
      // os.hideNavigationBarLoading({});
      that.setData({
        isEmpty: true,
        isLoading: false
      });
    });
  },

  /**
   * 获取观看数据
   */
  getSeenData: function(){
    let { currentPage, limit, dataList } = this.data;
    const data = db.getSeenHistoryLogs(currentPage, limit);

    let timeData = [];
    let isEnd = false;
    let isEmpty = false;
    let isLoading = false;

    if(data.current_page == 1){
      dataList = [];
      this.setData({seenList: data.list});
    }

    if(data.list.length > 0){
      dataList = dataList.concat(data.list);
    }

    if(data.current_page >= data.total_page && data.count > 0){
      isEnd = true;
    }

    if(data.current_page < data.total_page && data.count > 0){
      isLoading = true;
    }

    if(dataList.length == 0){
      isEmpty = true;
    } else {
      const tstime = getTsTimestamp();
      const ystime = getYsTimestamp();
      let today = {title: '今天', start_id: 0};
      let ytoday = {title: '昨天', start_id: 0};
      let gtoday = {title: '更早', start_id: 0};
      dataList.forEach(item => {
        if(item.update_time >= tstime){
          if(today.start_id == 0){
            today.start_id = item.id;
            timeData.push(today);
          }
        }
        if(item.update_time < tstime && item.update_time >= ystime){
          if(ytoday.start_id == 0){
            ytoday.start_id = item.id;
            timeData.push(ytoday);
          }
        }
        if(item.update_time < ystime){
          if(gtoday.start_id == 0){
            gtoday.start_id = item.id;
            timeData.push(gtoday);
          }
        }
      });
    }
    
    this.setData({
      dataList: dataList, 
      currentPage: parseInt(data.current_page), 
      pageTotal: data.total_page,
      timeData: timeData,
      isEnd: isEnd,
      isEmpty: isEmpty,
      isLoading: isLoading
    });
  },

  /**
   * 选择
   */
  onChecked: function(e){
    const idx = e.currentTarget.dataset.index;
    let dataList = this.data.dataList;
    dataList[idx].checked = !dataList[idx].checked;
    let checkedIds = dataList.filter(obj => obj.checked == true).map(obj => obj.id);
    this.setData({
      checkedAll: dataList.length == checkedIds.length ? true:false,
      dataList: dataList,
      checkedIds: checkedIds
    });
    return false;
  },

  /**
   * 全选
   */
  onCheckedAll: function(){
    this.checkedAll();
  },

  checkedAll: function(checked = null){
    if(checked === null){
      checked = !this.data.checkedAll;
    }
    let dataList = this.data.dataList.map(obj => {
      return { ...obj, checked: checked};
    });
    let checkedIds = dataList.filter(obj => obj.checked == true).map(obj => obj.id);
    this.setData({
      checkedAll: checked,
      dataList: dataList,
      checkedIds: checkedIds
    });
  },

  /**
   * 追剧/取消追剧
   */
  bindCollect(e){
    let currentVideo = e.currentTarget.dataset.item;
    // currentVideo.collect_id = currentVideo.is_collect;
    if(currentVideo.is_collect > 0){
      os.showModal({
        content: "是否取消追剧？",
        confirmText: "确认",
        cancelText: "关闭",
        confirmColor: "#f25c40",
        success(res) {
          if (res.confirm) {
            app.addAndDelCollect(currentVideo);
          }
        }
      });  
    }else{
      app.addAndDelCollect(currentVideo);
    }
  },

  /**
   * 更新追剧状态
   */
  onCollectUpdated(currentVideo, res) {
    let dataList = this.data.dataList;
    const index = dataList.findIndex(obj => obj.id === currentVideo.id);
    if (index !== -1) {
      Object.assign(dataList[index], res);
      this.setData({dataList: dataList});
      db.updateSeenHistoryLogs(currentVideo.id, res);
    }
  },

  /**
   * 移除
   */
  remove: function() {
    const that = this;
    const checkedIds = this.data.checkedIds;
    if(checkedIds.length > 0){
      os.showModal({
        title: that.data.dataType == 1 ? "是否取消追剧？":"是否移出「看过」？",
        content: that.data.dataType == 1 ? "取消后，追剧列表不再展示这部剧":"移出后，看过列表不再展示这部剧",
        confirmText: that.data.dataType == 1 ? "不再追剧":"移除",
        cancelText: "关闭",
        confirmColor: "#f25c40",
        success(res) {
          if (res.confirm) {
            os.showLoading({title: that.data.dataType == 1 ? "取消中...":"移出中..."});
            // 取消观看记录
            if (that.data.dataType == 2) {
              setTimeout(() => {
                db.delSeenHistoryLogs(checkedIds);
                os.hideLoading({});
                os.showTabBar();
                that.setData({
                  showEdit: false,
                  checkedAll: false,
                  currentPage: 1,
                  checkedIds: []
                });
                that.getDataList();
                app.Tips({title: '已移除', icon: 'success'});
              }, 1000);
              return;
            }

            // 取出剧目id
            let playletIds = [];
            checkedIds.forEach(id => {
              let item = that.data.dataList.find(obj => obj.id == id);
              if(item){
                playletIds.push(item.playlet_id);
              }
            });
            
            // 取消追剧
            api.delCollect({
              ids: checkedIds.join(','), 
              type: that.data.dataType
            }).then(res => {
              os.hideLoading({});
              if (res.code == 200) {
                os.showTabBar();
                that.setData({
                  showEdit: false,
                  checkedAll: false,
                  currentPage: 1,
                  checkedIds: []
                });
                that.getDataList();
                db.updateSeenHistoryLogs(playletIds, {is_collect: 0, collect_id: 0});
                return app.Tips({title: that.data.dataType == 1 ? '已取消追剧':'已移除', icon: 'success'});
              }else{
                return app.Tips({title: res.msg});
              }
            }).catch(err => {
              os.hideLoading({});
            });
          }
        }
      });  

      app.sendAppLogs('app', 4, {
        method_mark: 'remove',
        method_mark_1: '移除按钮'
      });
    }
  },

  /**
   * 跳到播放页
   */
  toVideoPage: function(e) {
    if(this.data.showEdit){
      return;
    }
    app.goPlayVideoPage(e.currentTarget.dataset.item.playlet_id);
  },

  /**
   * 编辑
   */
  toEdit: function(){
    if(this.data.showEdit == false){
      os.hideTabBar();
    }else{
      os.showTabBar();
    }
    this.setData({showEdit: !this.data.showEdit});
    this.checkedAll(false);
  },
  
  /**
   * IM的失败回调​​
   */
  onPlatformImError: function(e){
    app.Tips({
      title: "即将开通客服，请耐心等待"
    });
  },

  /**
   * IM的成功回调
   */
  onPlatformImSucess: function(e){
    app.sendAppLogs('app', 4, {
      method_mark: 'im',
      method_mark_1: '官方客服'
    });
  },

  /**
   * 加至桌面
   */
  addShortcutEvent: function(){
    if (e.detail.errNo == 0) {
      app.sendAppLogs('app', 4, {
        method_mark: 'addShortcut',
        method_mark_1: '加至桌面'
      });
    }
  },

  shareEvent: function(e){
    app.sendAppLogs('app', 4, {
      method_mark: 'share',
      method_mark_1: '分享'
    });
  },

  /**
   * 切换选项
   */
  onNavTap: function(e){
    const dataType = parseInt(e.currentTarget.dataset.value);
    const dataList = dataType == 1 ? this.data.collectList:this.data.seenList;
    let isEmpty = this.data.isEmpty;
    let isLoading = true;
    if(dataList.length > 0){
      isEmpty = false;
      isLoading = false;
    }
    this.setData({dataType: dataType, currentPage: 1, dataList: dataList, isEmpty: isEmpty, isLoading: isLoading});
    this.getDataList();
  },
  
  /**
   * 设置页面
   */
  toSetupPage: function(){
    os.navigateTo({
      url: '/pages/setup/setup'
    });
  },

  /**
   * 找短剧
   */
  toHomePage: function(){
    os.switchTab({
      url: '/pages/index/index'
    });
  },

  /**
   * 上滑加载
   */
  onloadPageData: function () {
    if(!this.data.showEdit){
      let currentPage = this.data.currentPage + 1;
      if (currentPage <= this.data.pageTotal){
        this.setData({currentPage: currentPage});
        this.getDataList();
      }
    }
  },

  /**
   * 页面滑动
   */
  onScroll: function(e) {
    const isFixedNav = e.detail.scrollTop > 120 ? true:false;
    if(isFixedNav !== this.data.isFixedNav){
      this.setData({isFixedNav: isFixedNav});
    }

    this.onSlideEvent(e);
  },

  /**
   * 滑动事件
   */
  onSlideEvent: function(e) {
    if (this.scrollHeight === undefined) {
      this.scrollHeight = [0, 0];
    }
    
    this.scrollHeight[1] = parseInt(e.detail.scrollTop);

    if (this.slideTimeId) {
      clearTimeout(this.slideTimeId);
    }
    
    this.slideTimeId = setTimeout(() => {
      clearTimeout(this.slideTimeId);

      if(this.scrollHeight[0] !== this.scrollHeight[1]){
        app.sendAppLogs('app', 5, {
          method_mark: this.scrollHeight[0],
          method_mark_1: this.scrollHeight[1],
        });
        this.scrollHeight[0] = this.scrollHeight[1];
      }

    }, 300);
  },

  /**
   * 分享
   */
  onShareAppMessage: function (shareOption) {
    return app.getShareAppMessage(shareOption);
  }

})